package com.huawang.mdesign.model.service.inter;

import com.huawang.mdesign.model.service.config.WebLog;
import com.huawang.mdesign.model.service.vo.ControllerStatistics;
import com.huawang.mdesign.model.service.vo.ControllerStatisticsVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Primary
public class ControllerStatisticsService {

    private final Map<String, ControllerStatistics> result = new HashMap<>(128);

    public void addRequestCount(WebLog log) {
        ControllerStatistics statistics = result.get(log.getUri());
        if(statistics == null) {
            statistics = new ControllerStatistics(log);
            result.putIfAbsent(log.getUri(), statistics);
        }

        statistics.addRequestCount();
        statistics.addSpendTimeList(log.getSpendTime());

    }

    @NotNull
    public List<ControllerStatisticsVo> queryRequestStatistics() {
        return result.keySet().stream().map(key -> {
            ControllerStatistics statistics = result.get(key);
            if(statistics == null) {
                return null;
            }

            ControllerStatisticsVo vo = new ControllerStatisticsVo();
            vo.setRequestCount(statistics.getRequestCount());
            vo.setUri(statistics.getUri());
            vo.setAverageTime(statistics.getAverageTime());
            vo.setNinetyAverageTime(statistics.getNinetyAverageTime());
            return vo;
        }).filter(Objects::nonNull)
                .sorted((o1, o2) -> {
                    if(Objects.equals(o1.getAverageTime(), o2.getAverageTime())) {
                        return 0;
                    } else {
                        return o1.getAverageTime() > o2.getAverageTime() ? -1 : 1;
                    }

                })
                .collect(Collectors.toList());
    }


}
